//
//  MGReceiptModel.m
//  MoneyRecord_iOS
//
//  Created by alchemy on 2022/1/13.
//  Copyright © 2022 Moneyease CO,. LTD. All rights reserved.
//

#import "MGRecordModel.h"

@implementation MGRecordModel

- (instancetype)init
{
    self = [super init];
    if (!self) return nil;
    
    _name = @"";
//    _startMoney = 1;
    _startDate = [NSDate date];
    _lastDays = 365;
    _gapMoney = 1;
    
    _receiptModels = [NSMutableArray new];
    _alertModel = [[MGAlertModel alloc] init];
    
    return self;
}

- (NSString *)getOssKey
{
    NSString *key = @(self.uniqueId).stringValue;
    // 以后共同记录的时候需要修改Key
    return [NSString stringWithFormat:@"%@/records/%@", self.create_userId, key];
}

- (void)setReceiptModels:(NSMutableArray *)receiptModels
{
    // 如果是JSON
    if (receiptModels.count > 0) {
        if ([receiptModels[0] isKindOfClass:[NSDictionary class]]) {
            _receiptModels = [NSArray yy_modelArrayWithClass:[MGReceiptModel class] json:receiptModels].mutableCopy;
        } else {
            _receiptModels = receiptModels;
        }
    } else {
        _receiptModels = receiptModels;
    }
}

- (NSArray *)getReceiptModelsWithBeginDate:(NSDate *)beginDate endDate:(NSDate *)endDate categoryUniqueId:(NSUInteger)categoryUniqueId accountUniqueId:(NSUInteger)accountUniqueId
{
    NSTimeInterval beginTime = beginDate.timeIntervalSince1970;
    NSTimeInterval endTime = endDate.timeIntervalSince1970;
    
    NSMutableArray *outputs = [NSMutableArray new];
    [outputs addObjectsFromArray:[self.receiptModels takeWhile:^BOOL(MGReceiptModel *obj) {
        NSTimeInterval objTime = [NSDate dateWithTimeIntervalSince1970:obj.actualSaveTime].startOfDay.timeIntervalSince1970;

        if (beginTime <= objTime && objTime <= endTime) {
            BOOL isSameAccount = obj.accountUniqueId == accountUniqueId;
            BOOL isSameCategory = obj.categoryUniqueId == categoryUniqueId;
            
            if (isSameAccount && isSameCategory) return YES;
            if (accountUniqueId == 0 && isSameCategory) return YES;
            if (isSameAccount && categoryUniqueId == 0) return YES;
            if (accountUniqueId == 0 && categoryUniqueId == 0) return YES;
        }
        return NO;
    }]];
    
    // 倒序输出
    [outputs sortUsingComparator:^NSComparisonResult(MGReceiptModel *obj1, MGReceiptModel *obj2) {
        if (obj1.actualSaveTime < obj2.actualSaveTime) {
            return NSOrderedDescending;
        }
        return NSOrderedAscending;
    }];
    
    return outputs;
}

- (NSDecimalNumber *)getWeeklyMoneyWithDate:(NSDate *)date isIncome:(BOOL)isIncome accountUniqueId:(NSUInteger)accountUniqueId categoryUniqueId:(NSUInteger)categoryUniqueId
{
    // 获取星期一的日期
    NSDate *startDateOfWeek = [date getStartDayOfWeek];
    NSDate *endDateOfWeek = [startDateOfWeek dateByAddingDays:6].endOfDay;
    
    NSArray *receiptModels = [self getReceiptModelsWithBeginDate:startDateOfWeek endDate:endDateOfWeek categoryUniqueId:categoryUniqueId accountUniqueId:accountUniqueId];
    NSArray *filterModels = [receiptModels takeWhile:^BOOL(MGReceiptModel *obj) {
        if (obj.receiptType == MGReceiptTypeIncome && isIncome) {
            return YES;
        } else if (obj.receiptType == MGReceiptTypePaid && !isIncome) {
            return YES;
        }
        return NO;
    }];
    
    return [MGRecordAccessor.shared sumMoneyOfReceiptModels:filterModels];
}

- (NSDecimalNumber *)getMonthlyMoneyWithDate:(NSDate *)date isIncome:(BOOL)isIncome accountUniqueId:(NSUInteger)accountUniqueId categoryUniqueId:(NSUInteger)categoryUniqueId
{
    NSDate *startDateOfMonth = [date startDayOfMonth];
    NSDate *endDateOfMonth = [date endDayOfMonth];
    
    NSArray *receiptModels = [self getReceiptModelsWithBeginDate:startDateOfMonth endDate:endDateOfMonth categoryUniqueId:categoryUniqueId accountUniqueId:accountUniqueId];
    NSArray *filterModels = [receiptModels takeWhile:^BOOL(MGReceiptModel *obj) {
        if (obj.receiptType == MGReceiptTypeIncome && isIncome) {
            return YES;
        } else if (obj.receiptType == MGReceiptTypePaid && !isIncome) {
            return YES;
        }
        return NO;
    }];
    
    return [MGRecordAccessor.shared sumMoneyOfReceiptModels:filterModels];
}

- (NSDecimalNumber *)getDayMoneyWithDate:(NSDate *)date accountUniqueId:(NSUInteger)accountUniqueId categoryUniqueId:(NSUInteger)categoryUniqueId
{
    NSDate *startDate = [date startOfDay];
    NSDate *endDate = [date endOfDay];
    
    NSArray *receiptModels = [self getReceiptModelsWithBeginDate:startDate endDate:endDate categoryUniqueId:categoryUniqueId accountUniqueId:accountUniqueId];
    NSArray *incomeModels = [receiptModels takeWhile:^BOOL(MGReceiptModel *obj) {
        if (obj.receiptType == MGReceiptTypeIncome) {
            return YES;
        }
        return NO;
    }];
    NSDecimalNumber *incomeValue = [MGRecordAccessor.shared sumMoneyOfReceiptModels:incomeModels];
    
    NSArray *outcomeModels = [receiptModels takeWhile:^BOOL(MGReceiptModel *obj) {
        if (obj.receiptType == MGReceiptTypePaid) {
            return YES;
        }
        return NO;
    }];
    NSDecimalNumber *outcomeValue = [MGRecordAccessor.shared sumMoneyOfReceiptModels:outcomeModels];
    
    NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
    return [incomeValue decimalNumberBySubtracting:outcomeValue withBehavior:roundUp];
}

- (NSArray *)getRecentReceiptModels:(NSUInteger)accountUniqueId categoryUniqueId:(NSUInteger)categoryUniqueId
{
    NSDate *date = [NSDate date].endOfDay;
    NSDate *beginDate = [[NSDate date].startOfDay dateByAddingDays:-30];
    NSArray *receipts = [self getReceiptModelsWithBeginDate:beginDate endDate:date categoryUniqueId:categoryUniqueId accountUniqueId:accountUniqueId];
    return receipts;
}

- (NSMutableArray *)getSortedRecentReceiptModels:(NSUInteger)accountUniqueId categoryUniqueId:(NSUInteger)categoryUniqueId
{
    NSMutableArray *receiptDateModels = [NSMutableArray new];
    
    NSArray *receiptModels = [self getRecentReceiptModels:accountUniqueId categoryUniqueId:categoryUniqueId];
    for (NSInteger index = 0; index < receiptModels.count; index ++) {
        MGReceiptModel *dataModel = receiptModels[index];
        
        NSDate *recordDate = [[NSDate dateWithTimeIntervalSince1970:dataModel.actualSaveTime] startOfDay];
        // 查询是否已经有model
        NSArray *dateModels = [receiptDateModels takeWhile:^BOOL(MGReceiptDateModel *obj) {
            if ([obj.startOfDay isEqualToDate:recordDate]) {
                return YES;
            }
            return NO;
        }];
        if (dateModels.count > 0) {
            // 已经存在
            MGReceiptDateModel *dateModel = dateModels.firstObject;
            if (dateModel) {
                [dateModel.dataModels addObject:dataModel];
            }
        } else {
            MGReceiptDateModel *dateModel = [[MGReceiptDateModel alloc] init];
            dateModel.startOfDay = recordDate;
            dateModel.date = [recordDate toStringWithFormatter:@"MM-dd"];
            [dateModel.dataModels addObject:dataModel];
            [receiptDateModels addObject:dateModel];
        }
    }
    return receiptDateModels;
}

- (void)createRecordProject
{
    NSMutableArray *receiptModels = [NSMutableArray new];
    for (NSInteger index = 0; index < 365; index ++)
    {
        MGReceiptModel *dataModel = [[MGReceiptModel alloc] init];
        
        CGFloat shouldSaveMoney = self.gapMoney * index;
        dataModel.shouldSaveMoney = [[NSDecimalNumber alloc] initWithFloat:shouldSaveMoney];
        dataModel.shouldSaveTime = [self.startDate dateByAddingDays:index].timeIntervalSince1970;
        
        [receiptModels addObject:dataModel];
    }
    
    self.receiptModels = receiptModels;
}

- (CGFloat)getShouldSaveMoney
{
    NSDecimalNumber *num = [[NSDecimalNumber alloc] initWithString:@"0"];
    for (MGReceiptModel *dataModel in self.receiptModels) {
        // 两位小数点后，只舍不入
        NSDecimalNumberHandler *roundUp = [NSDecimalNumberHandler decimalNumberHandlerWithRoundingMode:NSRoundPlain scale:2 raiseOnExactness:NO raiseOnOverflow:NO raiseOnUnderflow:NO raiseOnDivideByZero:YES];
        if (dataModel.shouldSaveMoney) {
            num = [num decimalNumberByAdding:dataModel.shouldSaveMoney withBehavior:roundUp];
        }
    }
    return num.floatValue;
}

- (CGFloat)getStoredMoney
{
    return [MGRecordAccessor.shared sumMoneyOfReceiptModels:self.receiptModels].floatValue;
}

@end
